package com.yulinlin.oss.controller;

import com.yulinlin.common.anno.JwtElement;
import com.yulinlin.common.domain.RequestPo;
import com.yulinlin.common.domain.ResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
@Api(tags="文件上传")
@RequestMapping("upload")
public class UploadController {

    @Value(("${upload.rootPath}"))
    private String rootPath;

    private String box="upload";


    private String getUploadPath(){
        return rootPath +File.separator+ box;
    }

    @ApiOperation("用户文件上传")
    @RequestMapping(value="uploadFile",method = RequestMethod.POST)
    public ResponseVo<String> uploadFile(String id , MultipartFile file) throws Exception {
        String contentType =  file.getContentType();
        String type =  contentType.split("/")[0];
        String url = "/"+box+"/"+id;
        File f =  new File(rootPath+url);
        if(!f.exists()){
            f.getParentFile().mkdirs();
            file.transferTo(f);
        }
        return ResponseVo.newInstance(url);
    }

    @ApiOperation("判断指定文件是否存在")
    @RequestMapping(value="hasFile",method = RequestMethod.POST)
    public ResponseVo<String>  hasFile(@RequestBody RequestPo<String> po) {
        String id = po.getData();
        String url = "/"+box+"/"+id;
        File f =  new File(url);
        if(f.exists()){
            return ResponseVo.newInstance(url);
        }
        return ResponseVo.newInstance("");

    }


    @JwtElement
    @ApiOperation("判断指定文件是否存在")
    @RequestMapping(value="test1",method = RequestMethod.GET)
    public ResponseVo<String>  test1(@RequestBody RequestPo<String> po) {

        return ResponseVo.newInstance("ok");

    }
    @JwtElement
    @RequestMapping("getUserInfo")
    public Object getUserInfo(){
        return SecurityContextHolder.getContext().getAuthentication();

    }


}
